package com.bawei.library_base

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Bundle
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.library_base.loadsir.*
import com.blankj.utilcode.util.ActivityUtils
import com.kingja.loadsir.core.LoadSir

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/1 16:17
 * @Description : BaseApplication
 */
open class BaseApplication:Application() {
    companion object{
        lateinit var instance:BaseApplication
    }

    override fun onCreate() {
        super.onCreate()
        setApplication()
    }
    /** 当宿主没有继承自该Application时,可以使用set方法进行初始化baseApplication */
    fun setApplication(){
        instance = this
        //ARouter初始化
        ARouter.openDebug();
        ARouter.openLog();
        ARouter.init(this);//注意！！！init放在后面
        //loadSir
        LoadSir.beginBuilder()
            .addCallback(ErrorCallback()) //失败
            .addCallback(EmptyCallback()) //空
            .addCallback(LoadingCallback()) //加载中
            .addCallback(TimeoutCallback()) //链接超时
            .addCallback(LottieLoadingCallback())//动画加载中
            .setDefaultCallback(LottieLoadingCallback::class.java) //设置默认状态页
            .commit()

        //注册activity生命周期的回调
        registerActivityLifecycleCallbacks(object :ActivityLifecycleCallbacks{
            //activity创建的时候放入堆栈中
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                AppManager.addActivity(activity)
            }

            override fun onActivityStarted(activity: Activity) {

            }

            override fun onActivityResumed(activity: Activity) {

            }

            override fun onActivityPaused(activity: Activity) {

            }

            override fun onActivityStopped(activity: Activity) {

            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

            }
            //移除堆栈
            override fun onActivityDestroyed(activity: Activity) {
              AppManager.removeActivity(activity)
            }
        })

    }
    /**
     * 获得当前进程的名字
     */
    fun getCurrentProcessName(context:Context):String{
        var activityManager =  context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager//获得activity系统服务
        var list =  activityManager.runningAppProcesses//获得当前正在运行的进程
        if(list == null || list.size == 0){
            return ""
        }
        //遍历当前正在运行的进程判断是不是和我进程id一样
        list.forEach {
            if(it.pid == android.os.Process.myPid()){
                return it.processName
            }
        }

        return ""

    }


}